using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.IO.Compression;
using System.Text.Json;

namespace Update.Services
{
    public class UpdateService
    {
        private readonly GiteeApi _giteeApi;
        private readonly string _currentVersion;
        private readonly string _updateTempPath;
        private readonly VersionInfo _versionInfo;

        public UpdateService(string owner, string repo, string currentVersion, string accessToken = null)
        {
            _giteeApi = new GiteeApi(owner, repo, accessToken);
            _currentVersion = currentVersion;
            _updateTempPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "SanmaoTools",
                "Updates"
            );
            _versionInfo = VersionInfo.Load();
        }

        public async Task<(bool hasUpdate, string newVersion, string updateInfo)> CheckForUpdatesAsync()
        {
            try
            {
                var latestRelease = await _giteeApi.GetLatestReleaseAsync();
                var latestVersion = latestRelease.TagName.TrimStart('v');

                // 使用本地保存的版本号进行比较
                bool hasUpdate = Version.Parse(latestVersion) > Version.Parse(_versionInfo.Version);
                
                // 如果已经是最新版本，直接启动SanmaoTools
                if (!hasUpdate)
                {
                    StartSanmaoTools();
                }
                
                return (hasUpdate, latestVersion, latestRelease.Body);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"检查更新失败: {ex.Message}");
                throw;
            }
        }

        public async Task DownloadAndInstallUpdateAsync(IProgress<(long current, long total)> progress = null)
        {
            string updateFilePath = string.Empty;
            string extractPath = string.Empty;

            try
            {
                // 获取应用程序目录的完整路径
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;

                var release = await _giteeApi.GetLatestReleaseAsync();
                if (release.Assets == null || release.Assets.Length == 0)
                {
                    throw new Exception("未找到更新包");
                }

                var updatePackage = release.Assets[0];
                var updateBytes = await _giteeApi.DownloadReleaseAssetAsync(updatePackage.BrowserDownloadUrl, progress);

                // 确保临时目录存在
                Directory.CreateDirectory(_updateTempPath);

                // 保存更新包
                updateFilePath = Path.Combine(_updateTempPath, updatePackage.Name);
                await File.WriteAllBytesAsync(updateFilePath, updateBytes);

                // 创建解压目录
                extractPath = Path.Combine(_updateTempPath, "extracted");
                if (Directory.Exists(extractPath))
                {
                    Directory.Delete(extractPath, true);
                }
                Directory.CreateDirectory(extractPath);

                // 解压更新包
                ZipFile.ExtractToDirectory(updateFilePath, extractPath);

                // 获取更新文件目录
                string updateFilesPath = Path.Combine(extractPath, "net8.0-windows");
                if (!Directory.Exists(updateFilesPath))
                {
                    throw new Exception("更新包格式错误：未找到net8.0-windows目录");
                }

                // 关闭所有可能占用文件的进程
                foreach (var process in Process.GetProcessesByName("SanmaoTools"))
                {
                    try
                    {
                        process.Kill();
                        process.WaitForExit(5000); // 等待进程退出，最多等待5秒
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"关闭进程失败: {ex.Message}");
                    }
                }

                // 复制更新文件
                CopyDirectory(updateFilesPath, appDirectory);

                // 保存新版本号到本地
                VersionInfo.Save(release.TagName.TrimStart('v'));

                // 清理临时文件
                try
                {
                    if (Directory.Exists(extractPath))
                    {
                        Directory.Delete(extractPath, true);
                    }
                    if (File.Exists(updateFilePath))
                    {
                        File.Delete(updateFilePath);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"清理临时文件失败: {ex.Message}");
                }

                // 启动更新后的程序
                StartSanmaoTools();

                // 关闭当前应用程序
                Application.Current.Shutdown();
            }
            catch (Exception ex)
            {
                // 如果下载或保存过程中出错，清理已下载的文件
                if (!string.IsNullOrEmpty(updateFilePath) && File.Exists(updateFilePath))
                {
                    try { File.Delete(updateFilePath); } catch { }
                }
                if (!string.IsNullOrEmpty(extractPath) && Directory.Exists(extractPath))
                {
                    try { Directory.Delete(extractPath, true); } catch { }
                }

                Debug.WriteLine($"下载更新失败: {ex.Message}");
                throw;
            }
        }

        private void CopyDirectory(string sourceDir, string targetDir)
        {
            // 确保目标目录存在
            Directory.CreateDirectory(targetDir);

            // 复制所有文件
            foreach (string file in Directory.GetFiles(sourceDir))
            {
                string fileName = Path.GetFileName(file);
                string destFile = Path.Combine(targetDir, fileName);
                try
                {
                    File.Copy(file, destFile, true);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"复制文件失败 {fileName}: {ex.Message}");
                }
            }

            // 递归复制所有子目录
            foreach (string dir in Directory.GetDirectories(sourceDir))
            {
                string dirName = Path.GetFileName(dir);
                string destDir = Path.Combine(targetDir, dirName);
                CopyDirectory(dir, destDir);
            }
        }

        private void StartSanmaoTools()
        {
            try
            {
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string exePath = Path.Combine(appDirectory, "SanmaoTools.exe");
                
                if (File.Exists(exePath))
                {
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = exePath,
                        UseShellExecute = true
                    });
                    Application.Current.Shutdown();
                }
                else
                {
                    Debug.WriteLine($"找不到SanmaoTools.exe: {exePath}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"启动SanmaoTools失败: {ex.Message}");
            }
        }
    }
} 